<?php

namespace GuanChanghu\Library\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

/**
 * Class Language
 * @tag encryption free
 * @package GuanChanghu\Library\Http\Middleware
 */
class Language
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $localeDefault = config('app.locale_default');
        $locale = config('app.locale');
        $language = $request->header('x-language');

        if ($language && $locale !== $language) { // 客户端有需要更换语言  &&  当前语言和客户端不一致,准备更换
            $locales = config('app.locales');
            if (in_array($locale, $locales, true)) { // 客户端需要的语言在服务器支持的语言里,更换
                config(['app.locale' => $language]);
            } else if ($locale !== $localeDefault) {
                config(['app.locale' => $language]);
            }

        } else if ($locale !== $localeDefault) {
            config(['app.locale' => $language]);
        }

        return $next($request);
    }
}
